package com.wx.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * BIO: blocking IO
 * @author wangxun
 * @version 1.0
 * @description: 阻塞的IO模型
 * @date 2020/12/30 4:04 下午
 */
public class SocketBioServer {
    public static void main(String[] args) throws IOException {
        // 9090 端口号 backlog 等待队列最大长度
        ServerSocket serverSocket = new ServerSocket(9999, 20);
        System.out.println(Thread.currentThread().getName()+": serverSocket is starting");
        while (true){
            // 阻塞接收客户端请求,建立与客户端对应的socket
            Socket client = serverSocket.accept();
            System.out.println(Thread.currentThread().getName()+": "+client.getRemoteSocketAddress()+" is linking...");
            // 抛出一个新的线程,去处理客户端通讯
            new Thread(()->{
                InputStream is ;
                try {
                    is = client.getInputStream();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    while (true){
                        // 阻塞接收
                        String dataLine = reader.readLine();
                        if (dataLine != null) {
                            System.out.println(Thread.currentThread().getName()+": receive :"+dataLine);
                        }else{
                            client.close();
                            break;
                        }
                    }
                    System.out.println(Thread.currentThread().getName()+": "+client.getRemoteSocketAddress()+" is closed...");

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
